package com.example.consumer.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.example.consumer.service.TestService;
import com.example.entity.UserTest;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author tianzhuang
 * @version 1.0
 * @date 2021/11/7 23:26
 */
@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private RabbitTemplate rabbitTemplate;



    private final String queue = "testqueue";

    private final String exchange = "testexchange";

    private final String exchange1 = "testexchange1";

    private final String exchange2 = "testexchange2";



    @Override
    public void sendMessage() {
        rabbitTemplate.convertAndSend(queue, "this is a test message");
    }

    @Override
    public void sendMessage(UserTest user) {
        System.err.println("发送的消息为："+user.toString());
        rabbitTemplate.convertAndSend(queue, JSONObject.toJSONString(user));
//        rabbitTemplate.convertAndSend(queue, SerializationUtils.serialize(user));
    }


    @Override
    public void sendExchangeMessage(UserTest user) {
        System.err.println("发送的消息为："+user);
        rabbitTemplate.convertAndSend(exchange, "", JSONObject.toJSONString(user));
    }

    @Override
    public void sendExchangeMessageByKey(UserTest user) {
        System.err.println("发送的消息为："+user);
        rabbitTemplate.convertAndSend(exchange1, "a", JSONObject.toJSONString(user));
    }


    // 定义 * 号路由，仅能匹配一个单词
    private String logStart = "log.register";

    // 定义 # 号路由，能匹配0个或多个单词
    private String logHash = "log.register.error";

    /**
     * logStart 形式的log.*和log.#都可以匹配到
     * logHash 形式的只有log.#可以匹配到
     * 交换机类型必须为topic
     *
     * @param user
     */
    @Override
    public void sendExchangeMessageByTopic(UserTest user) {

        try {
            System.err.println("发送的消息为："+user);
            rabbitTemplate.convertAndSend(exchange2, logHash, JSONObject.toJSONString(user));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
